<template>
	<view>
		<cu-custom bgColor="bg-gradual-pink" :isBack="true">
			<block slot="backText">返回</block><block slot="content">{{title}}</block>
		</cu-custom>
		<view class="cu-chat">
			<view v-for="(item,index) in chatList">
				
				<view class="cu-item self" v-if="username == item.from_id">
					<view class="main">
						<view class="content bg-green shadow" v-if="(item.msg_type == 'image')">
							<image :src="item.image" class="radius" mode="widthFix" @click="openimage(item.msg_id)"></image>
						</view>
						<view class="content bg-green shadow" v-else>
							<text>{{item.text}}</text>
						</view>
					</view>
					<view class="cu-avatar radius" :style="[{background: 'url('+item.avatar+')'}]"></view>
					<view class="date">{{item.time}}</view>
				</view>
				<view class="cu-item" v-else>
					<view class="cu-avatar radius" :style="[{background: 'url('+item.avatar+')'}]"></view>
					<view class="main">
						<view class="content shadow" v-if="(item.msg_type == 'image')">
							<image :src="item.image" class="radius" mode="widthFix" @click="openimage(item.msg_id)"></image>
						</view>
						<view class="content shadow" v-else>
							<text>{{item.text}}</text>
						</view>
					</view>
					<view class="date ">{{item.time}}</view>
				</view>
			</view>
		</view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]">
			<!-- <view class="action">
				<text class="cuIcon-sound text-grey"></text>
			</view> -->
			<input class="solid-bottom" :adjust-position="false" :focus="false" maxlength="300" cursor-spacing="10"
			 @focus="InputFocus" @blur="InputBlur" v-model="my_say_text"></input>
			<view class="action">
				<text class="cuIcon-pic text-grey" @click="to_send_pic()"></text>
			</view>
			<button class="cu-btn bg-green shadow" @click="to_send()">发送</button>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				InputBottom: 0,
				chater_info:{},
				title:"聊天",
				chatList:[],
				username:"",
				userinfo:{},
				my_say_text:'',
			};
		},
		onLoad(){
			let _this = this
			var chater_info = uni.getStorageSync('jiguang_chater_info')
			// console.log(chater_info)
			this.chater_info = chater_info
			this.title = chater_info.nickName
			this.username = uni.getStorageSync('jim_login_username')
			
			this.$jjim.config('jztuan_dev_corp_3','jztuan_dev_corp_3')
			this.$jjim.login()
			this.$jjim.getUserInfo().then(function(data){
				_this.userinfo = data.user_info
				
				_this.getMsgs()
				// _this.loadHistory()
			})
			
			uni.$on('msg_ol', function(data) {
				console.log('收到消息，收到消息，收到消息')
				console.log(data)
				for(var i = 0;i<data.length;i++)
				{
					if(data[i].content.from_id == _this.chater_info.username){
						_this.insertData(data[i])	
					}
				}
				_this.loadReources()
				_this.to_bottom()
			})
		},
		methods: {
			insertData(item){				
				let _this = this
				item.from_id = item.content.from_id
				item.msg_type =  item.content.msg_type
				item.text = item.content.msg_body.text
				if(item.content.from_id == _this.username){
					item.avatar = _this.userinfo.avatar
				}else{
					item.avatar = _this.chater_info['avatar']
				}
				_this.chatList.push(item)
			},
			getMsgs(){
				let _this = this
				let msgs = this.$jjim.getMsgs(this.chater_info.username)
				msgs = msgs.sort(_this.timeAsc)
				for(var i = 0;i<msgs.length;i++)
				{
					msgs[i].from_id = msgs[i].content.from_id
					msgs[i].msg_type =  msgs[i].content.msg_type
					msgs[i].text = msgs[i].content.msg_body.text
					if(msgs[i].content.from_id == this.username){
						msgs[i].avatar = this.userinfo.avatar
					}else{
						msgs[i].avatar = this.chater_info['avatar']
					}
				}
				
				_this.chatList = msgs
				_this.chatList.sort(_this.timeAsc)
				_this.loadReources()
				_this.to_bottom()
			},
			loadReources(){
				let _this = this
				for(var i=0;i<_this.chatList.length;i++){
					if(_this.chatList[i].content.msg_type == 'image' && !_this.chatList[i].image){
						let _c = _this.chatList[i]
						// console.log('start:' + i + '-' + _this.chatList.length)
						_this.$jjim.getResurce(_this.chatList[i].content.msg_body.media_id, i).then(function(data){
							_c.image = data.url
							_this.chatList[data.index] = _c
							_this.chatList.sort(_this.timeAsc)
						},function(data){
							console.log('图片加载失败：'+JSON.stringify(data))
						})
					}
				}
			},
			loadMsgs(msgs){
				let _this = this
				if(msgs){
					msgs = msgs.sort(_this.timeAsc)
					for(var i = 0;i<msgs.length;i++)
					{
						msgs[i].from_id = msgs[i].content.from_id
						msgs[i].msg_type =  msgs[i].content.msg_type
						msgs[i].text = msgs[i].content.msg_body.text
						if(msgs[i].content.from_id == this.username){
							msgs[i].avatar = this.userinfo.avatar
						}else{
							msgs[i].avatar = this.chater_info['avatar']
						}
						if(msgs[i].content.msg_type == 'image'){
							let _c = msgs[i]
							_this.$jjim.getResurce(msgs[i].content.msg_body.media_id).then(function(data){
								_c.image = data
								_this.chatList[i] = _c
								_this.chatList.sort(_this.timeAsc)
							},function(data){
								console.log('图片加载失败：'+JSON.stringify(data))
							})
						}
					}
					console.log(msgs)
					this.chatList = msgs
					_this.to_bottom()
				}else{
					//获取历史消息
					this.loadHistory()
				}
			},
			loadHistory(){
				let _this = this
				_this.$jjim.getHistory().then(function(data){
					for(var i=0;i<data.data.messages.length;i++){
						data.data.messages[i].text = data.data.messages[i].msg_body.text
						if(data.data.messages[i].from_id == _this.username){
							data.data.messages[i].avatar = _this.userinfo.avatar
						}else{
							data.data.messages[i].avatar = _this.chater_info['avatar']
						}
						
						if(data.data.messages[i].msg_type == 'image'){
							let _c = data.data.messages[i]
							_this.$jjim.getResurce(data.data.messages[i].msg_body.media_id).then(function(data){
								_c.image = data
								_this.chatList[i] = _c
								_this.chatList.sort(_this.timeAsc)
							},function(data){
								console.log('图片加载失败：'+JSON.stringify(data))
							})
						}
					}
					_this.chatList = data.data.messages 
					_this.to_bottom()
					
				},function(data){
					console.log(data)
					_this.loadHistory()
				});
			},
			openimage(msg_id){
				let _this = this;
				let urls = [];
				let current = 0;
				for(var i=0;i<_this.chatList.length;i++){
					if(_this.chatList[i].msg_type == 'image'){
						if(msg_id == _this.chatList[i].msg_id){
							current = urls.length
						}
						urls.push(_this.chatList[i].image)
					}
				}
				// console.log(urls)
				uni.previewImage({
					urls: urls,
					current: current
				});
			},
			to_bottom() {
				setTimeout(function() {
					uni.pageScrollTo({
						scrollTop: 100000,
						duration:0
					})
				}, 500);
			},
			to_send() {
				var _this = this;
				if (!_this.my_say_text || _this.my_say_text == '') {
					//无内容直接跳出
					return
				}
				this.$jjim.sendMsg(_this.chater_info.username,_this.chater_info.nickName,_this.my_say_text).then(function(data){
					_this.insertData(data)
					_this.to_bottom()
					_this.my_say_text = ''
				},function(error){
					console.log(error)
					_this.my_say_text = ''
				})
			},
			to_send_pic(){
				let _this = this
				
				uni.chooseImage({
					count:1,
					// sizeType:  original 原图，compressed 压缩图，默认二者都有
					sizeType: ['original', 'compressed'],
					success(res){
						uni.showLoading({
							title:'上传中...'
						})
						let img = res.tempFilePaths[0]
						
						_this.$jjim.sendPic(_this.chater_info.username,_this.chater_info.nickName, img).then(function(data){
							_this.insertData(data)
							_this.loadReources()
							_this.to_bottom()
							uni.hideLoading()
						},function(error){
							console.log(error)
							uni.hideLoading()
						})
					} 
				})
			},
			timeAsc(obj1,obj2){
				if(obj1.ctime_ms < obj2.ctime_ms){
				   return -1;
				}else if(obj1.ctime_ms > obj2.ctime_ms){
				   return 1;
				}else{
				   return 0;
				}
			},
			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			}
		}
	}
</script>

<style>
page{
  padding-bottom: 100upx;
}
	.cu-avatar{
		background-size: 100% 100% !important;
		background-color:#EEE !important;
	}
</style>
